package com.tanhua.server.interceptor;


import com.fasterxml.jackson.databind.ObjectMapper;

import com.tanhua.common.utils.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.concurrent.TimeUnit;

@ControllerAdvice
public class MyResponseBodyAdvice implements ResponseBodyAdvice {

    @Value("${tanhua.cache.enable}")
    private Boolean enable;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    // 判断是否支持该操作
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        //开关，方法，cache ，符合条件 调用beforeBodyWrite方法
        return enable
                && methodParameter.hasMethodAnnotation(GetMapping.class)
                && methodParameter.hasMethodAnnotation(Cache.class);
    }

    // 在输出之前做具体操作
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter,
                                  MediaType mediaType, Class aClass,
                                  ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        if (body == null) {
            return null;
        }

        try {
            String redisValue = null;
            if (body instanceof String) {
                redisValue = (String) body;
            } else {
                redisValue = MAPPER.writeValueAsString(body);
            }
            String redisKey = RedisCacheInterceptor.
                    createRedisKey(((ServletServerHttpRequest) serverHttpRequest).getServletRequest());

            Cache cache = methodParameter.getMethodAnnotation(Cache.class);
            Long time = Long.valueOf(cache.time());
            //缓存单位是秒,与cache过期时间相同
            this.redisTemplate.opsForValue().set(redisKey, redisValue, time, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return body;
    }
}
